package com.xxx.yuedong.mine.controller;


import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONUtil;
import com.xxx.yuedong.common.R;
import com.xxx.yuedong.mine.controller.form.UpdatePointsForm;
import com.xxx.yuedong.mine.pojo.User;
import com.xxx.yuedong.mine.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;


@RestController
@RequestMapping("/user")
@Slf4j
public class PointsController {

    @Autowired
    private UserService userService;


    @GetMapping("/addPoints/{pointsToAdd:[0-9]+}")
    @SaCheckLogin
    public R addPoints(@PathVariable("pointsToAdd") int pointsToAdd){
        long userId = Long.parseLong((String) StpUtil.getLoginId());
        if (userService.addPoints(userId, pointsToAdd) <= 0) {
            return R.error("新增积分失败！");
        }
        return R.ok();
    }

    @PostMapping("/updatePoints")
    public R updatePoints(@Valid @RequestBody UpdatePointsForm form){
        Integer currentPoints = userService.searchUserPoints(StpUtil.getLoginIdAsLong());
        Integer points = currentPoints - form.getPoints();
        HashMap param = new HashMap();
        param.put("points",points);
        param.put("id",StpUtil.getLoginIdAsInt());

        Integer rows = userService.updatePoints(param);
        return R.ok().put("rows",rows);
    }
}
